package com.tdam2013.grupo12.adapters;

import java.util.ArrayList;

import com.tdam2013.grupo12.MiWidget;
import com.tdam2013.grupo12.R;
import com.tdam2013.grupo12.clasesDeNegocio.Accion;
import com.tdam2013.grupo12.clasesDeNegocio.BaseDeDatos;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService.RemoteViewsFactory;

public class WidgetRemoteViewsAdapter implements RemoteViewsFactory {

private Context context = null;
private int appWidgetId;
private BaseDeDatos db;
private ArrayList<Accion> llamadas = new ArrayList<Accion>();

public WidgetRemoteViewsAdapter(Context context, Intent intent) {
    this.context = context;
    appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
            AppWidgetManager.INVALID_APPWIDGET_ID);
    
}

public int getCount() {
    return llamadas.size();
}

public long getItemId(int position) {
    return position;
}

public RemoteViews getLoadingView() {
    // TODO Auto-generated method stub
    return null;
}

public RemoteViews getViewAt(int position) {
    String telefono = "";
	RemoteViews row = new RemoteViews(context.getPackageName(),
            R.layout.activity_item_widget);

    row.setTextViewText(R.id.contacto, llamadas.get(position)
            .getNombreContacto());
    
    Cursor cursorTelefonos = context.getContentResolver().query(
			ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
			null,
			ContactsContract.CommonDataKinds.Phone.CONTACT_ID
					+ " = ?",
			new String[] { llamadas.get(position).getIdContacto()+"" }, null);
	if (cursorTelefonos.moveToNext()) {
		telefono = cursorTelefonos.getString(cursorTelefonos
				.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
	}
    
	Bundle extras = new Bundle();
    extras.putString(MiWidget.EXTRA_ITEM, telefono);
    Intent fillInIntent = new Intent();
    fillInIntent.putExtras(extras);
    // Make it possible to distinguish the individual on-click
    // action of a given item
    row.setOnClickFillInIntent(R.id.contacto, fillInIntent);
    return (row);
}

public int getViewTypeCount() {
    // TODO Auto-generated method stub
    return 1;
}

public boolean hasStableIds() {
    // TODO Auto-generated method stub
    return false;
}

public void onCreate() {
	db = new BaseDeDatos(context);
	llamadas = db.getUltimasLlamadas();
}

public void onDataSetChanged() {
	llamadas = db.getUltimasLlamadas();
}

public void onDestroy() {
    // TODO Auto-generated method stub

}

}
